package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"sync"
	"time"

	"github.com/gin-gonic/gin"
	"go-papers/common/go-wechat/common"
	"go-papers/models"
	"go-papers/notice"
	"go-papers/pkg/lognew"
	"go-papers/pkg/wechat"
	"go-papers/tools"
)

func GetTradeNo(orderId int, p string) string {
	// 1 + 8 + 19+ 4 = 32
	outTrade := p + time.Now().Format("20060102") + "U" + tools.IntToString(orderId) + tools.RandString(4)
	return outTrade
}

// 订单支付成功后：
func OrderChangeInfo(oid int) {

	var order models.Order
	orderInfo, _ := order.GetByID(oid)

	//1.更新 用户累计 订单数 与 金额
	var mem models.Member
	memInfo, err := mem.GetByID(orderInfo.MemberId)
	if err == nil {
		memInfo.TotalOrderNums += 1
		memInfo.TotalPrice += orderInfo.OrderPrice
		_, err = memInfo.Update(memInfo.MemberId)
		if err != nil {
			lognew.Error(context.TODO(), "MemberUpdate", lognew.Fields{"order_id": orderInfo.OrderId, "member_id": orderInfo.MemberId, "err": err.Error()})
		}
	} else {
		lognew.Error(context.TODO(), "MemberGetByID", lognew.Fields{"order_id": orderInfo.OrderId, "member_id": orderInfo.MemberId, "err": err.Error()})
	}

	//5更新课程 ：订单数
	var course models.Course
	courseInfo, err := course.GetById(orderInfo.CourseId)
	if err != nil {
		lognew.Error(context.TODO(), "courseGetByID--Error", lognew.Fields{"course_id": orderInfo.CourseId, "order_id": orderInfo.OrderId, "organ_id": orderInfo.OrganId, "err": err.Error()})
	} else {
		courseInfo.CourseOrderPrice += orderInfo.OrderPrice
		courseInfo.CourseOrderNum += 1
		courseInfo.CourseOrderSurePrice += orderInfo.ShareOrganPrice
		_, err = courseInfo.Update(orderInfo.CourseId)
	}

	//4.更新机构：订单数
	var organ models.Organ
	organInfo, err := organ.GetByID(orderInfo.OrganId)
	if err != nil {
		lognew.Error(context.TODO(), "organGetByID", lognew.Fields{"order_id": orderInfo.OrderId, "organ_id": orderInfo.OrganId, "err": err.Error()})
		return
	}

	organInfo.OrganCourseOrder += 1
	_, _ = organInfo.Update(orderInfo.OrganId)

	bid := organInfo.OrganBrandId
	if bid > 0 {
		//3.更新品牌 订单数量
		var brand models.OrganBrand
		brandInfo, err := brand.GetByID(bid)
		if err == nil {
			brandInfo.BrandOrderNums += 1
			_, _ = brandInfo.Update(bid)
		}
	}
}

// 订单退款 更新数据 courseInfo.CourseOrderSureRefund += orderInfo.ShareOrganRefund
func OrderChangeInfoRefund(orderInfo models.Order, refundPrice float64) {
	//1.更新 用户累计 订单数 与 金额
	//var mem models.Member
	//memInfo, err := mem.GetByID(orderInfo.MemberId)
	//if err == nil {
	//    memInfo.TotalOrderNums -= 1
	//    memInfo.TotalPrice -= orderInfo.OrderPrice
	//    _, err = memInfo.Update(memInfo.MemberId)
	//    if err != nil {
	//        lognew.Error(context.TODO(), "MemberUpdate", lognew.Fields{"order_id": orderInfo.OrderId,
	//         "member_id": orderInfo.MemberId, "err": err.Error()})
	//    }
	//} else {
	//    lognew.Error(context.TODO(), "MemberGetByID", lognew.Fields{"order_id": orderInfo.OrderId,
	//     "member_id": orderInfo.MemberId, "err": err.Error()})
	//}

	//5更新课程 ：订单数
	var course models.Course
	courseInfo, err := course.GetById(orderInfo.CourseId)

	lognew.Info(context.TODO(), "OrderChangeInfoRefund", lognew.Fields{"course_id": orderInfo.CourseId,
		"order_id":         orderInfo.OrderId,
		"ShareOrganRefund": orderInfo.ShareOrganRefund, "RefundPrice": refundPrice})

	if err != nil {
		lognew.Error(context.TODO(), "courseGetByID--Error", lognew.Fields{"course_id": orderInfo.CourseId,
			"order_id": orderInfo.OrderId, "organ_id": orderInfo.OrganId, "err": err.Error()})
	} else {
		courseInfo.CourseOrderSureRefund += orderInfo.ShareOrganRefund
		courseInfo.CourseOrderRefund += refundPrice
		_, err = courseInfo.Update(orderInfo.CourseId)
	}

	////4.更新机构：订单数
	//var organ models.Organ
	//organInfo, err := organ.GetByID(orderInfo.OrganId)
	//if err != nil {
	//    lognew.Error(context.TODO(), "organGetByID", lognew.Fields{"order_id": orderInfo.OrderId,
	//     "organ_id": orderInfo.OrganId, "err": err.Error()})
	//    return
	//}

	//organInfo.OrganCourseOrder += 1
	//_, _ = organInfo.Update(orderInfo.OrganId)
	//
	//bid := organInfo.OrganBrandId
	//if bid > 0 {
	//    //3.更新品牌 订单数量
	//    var brand models.OrganBrand
	//    brandInfo, err := brand.GetByID(bid)
	//    if err == nil {
	//        brandInfo.BrandOrderNums += 1
	//        _, _ = brandInfo.Update(bid)
	//    }
	//}
}

func GetPrepayId(c *gin.Context, orderId int, openId string, needRepeat bool) (*common.UnifyOrderResult, error) {

	// 是否需要重新计算价格 @TODO
	if needRepeat {

	}

	//订单信息
	var order models.Order
	order.OrderId = orderId
	orderInfo, _ := order.Get()

	//贸易单号
	outTrade := GetTradeNo(orderId, "P")
	body := orderInfo.OrderName

	loo := show_strlen(body)
	if loo > 60 {
		body = show_substr(body, 60)
	}

	lognew.Debug(context.TODO(), "GetPrepayId", lognew.Fields{"body": body, "OrderName": orderInfo.OrderName, "orderId": orderId, "loo": loo})

	//下单
	payData := common.UnitOrder{
		Base: common.Base{
			SubMchId: orderInfo.OrganPayAccount,
		},
		Body:           body,
		NotifyUrl:      wechat.Server.WechatPay().GetNotifyUrl(),
		TradeType:      "JSAPI",
		SpbillCreateIp: c.ClientIP(),
		TotalFee:       int(orderInfo.OrderPrice * 100),
		OutTradeNo:     outTrade,
		SceneInfo:      "",
		FeeType:        "",
		Openid:         openId,
		Referer:        "",
	}
	//JSAPI -JSAPI支付
	//
	//NATIVE -Native支付
	//
	//APP -APP支付
	resp, err := wechat.Server.WechatPay().Pay(&payData)

	result, _ := json.Marshal(resp)
	pp, _ := json.Marshal(payData)
	//生产 trade 订单记录
	orderTrade := models.OrderTrade{
		OrderId:       orderInfo.OrderId,
		TradeMemberId: orderInfo.MemberId,
		TradeNo:       outTrade,
		TradePrice:    orderInfo.OrderPrice,
		TradeBody:     body,
		TradeAppId:    payData.AppId,
		TradeMechId:   payData.MchId,
		TradeOpenId:   payData.Openid,
		TradeStart:    time.Now().Format("2006-01-02 15:04:05"),
		TradeCallUrl:  payData.NotifyUrl,
		TradeResult:   string(result),
		TradeInfo:     string(pp),
		TradeStatus:   "1",
	}
	_, err = orderTrade.Create()
	if err != nil {
		lognew.Info(context.TODO(), "tradeInfoLog", lognew.Fields{"error": err.Error(), "orderTrade": orderTrade})
	}

	// 订单信息
	return resp, err
}

func GetPaySign(m map[string]interface{}, source string) string {
	return wechat.Server.WechatPay().GetPaySign(m)
}

func OrderShareHandle(oid int) (bool, string) {
	msg := ""
	//订单信息
	var order models.Order
	orderInfo, err := order.GetByID(oid)
	if err != nil {
		msg = "订单信息查询异常"
		lognew.Error(context.TODO(), "OrderShareHandle1", lognew.Fields{"oid": oid, "msg": "订单信息查询异常", "err": err.Error()})
		return false, msg
	}
	//根据订单信息  获取对应数据
	organId := orderInfo.OrganId
	memberId := orderInfo.MemberId

	//分别获取
	var organ models.Organ
	organInfo, err := organ.GetByID(organId)
	if err != nil {
		msg = "机构信息查询异常"
		lognew.Error(context.TODO(), "OrderShareHandle2", lognew.Fields{"oid": oid, "msg": "机构信息查询异常", "err": err.Error()})
		return false, msg
	}

	var member models.Member
	memberInfo, err := member.GetByID(memberId)
	if err != nil {
		msg = "会员信息查询异常"
		lognew.Error(context.TODO(), "OrderShareHandle3", lognew.Fields{"oid": oid, "msg": "会员信息查询异常", "err": err.Error()})
		return false, msg
	}

	// 佣金设置 配置
	var comm models.CommonCfg
	cfg := comm.GetCfg() // share

	//分别得到 机构佣金 分成比例
	organRate := organInfo.OrganRate
	if organRate <= 0 {
		msg = "机构佣金比例设置异常"
		lognew.Error(context.TODO(), "OrderShareHandle4", lognew.Fields{"oid": oid, "msg": "机构佣金比例设置异常"})
		return false, msg
	}
	if organRate >= 100 {
		organRate = 100
	}
	ShareOrganRate := (100 - organRate) / 100.0
	ShareOrganPrice := ShareOrganRate * orderInfo.OrderPrice

	lognew.Info(context.TODO(), "OrderShareHandle-share", lognew.Fields{"oid": oid, "organRate": organRate,
		"ShareOrganRate": ShareOrganRate, "ShareOrganPrice": ShareOrganPrice, "cfg": cfg})

	//最大限制
	firstRate := organRate
	if firstRate > 30 {
		firstRate = 30
	}

	ShareMomOrganPrice := 0.0
	ShareMomOrganRate := 0.0
	organMomId := organInfo.OrganMomId
	if organMomId > 0 {
		ShareMomOrganRate = organRate * cfg.OrganRate / 10000.0
		ShareMomOrganPrice = ShareMomOrganRate * orderInfo.OrderPrice
	}

	momLevel := ""
	momRealName := memberInfo.MomRealName
	ShareMomMemberRate := 0.0
	ShareMomMemberPrice := 0.0
	memberMomId := memberInfo.MomUserId
	if memberMomId > 0 {
		ShareMomMemberRate = (organRate * (100 - cfg.OrganRate)) / 10000.0
		ShareMomMemberPrice = ShareMomMemberRate * orderInfo.OrderPrice

		var mom models.MemberMom
		momInfo, _ := mom.GetByMID(memberMomId)
		momLevel = momInfo.MomLevel // OrderShareHandle
	}

	organNowRate := (100 - firstRate) / 100.0
	organNowPrice := organNowRate * orderInfo.OrderPrice
	// ShareType 类型 1平台与机构 2 社区达人与拓展用户 3 社区达人与拓展机构
	// ShareStatus 分成状态 1  待确认  5 已确认/已打款   10 待退回 20 已退回  50 已关闭
	oragnShare := models.OrderShare{
		OrderId:             orderInfo.OrderId,
		ShareName:           "机构",
		ShareStatus:         "1",
		ShareDesc:           "机构课程费用收入",
		ShareInfo:           "",
		SharePrice:          organNowPrice,
		ShareRate:           organNowRate,
		ShareType:           "1",
		ShareUserId:         0,
		ShareTo:             0,
		ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
		ShareMomOrganPrice:  ShareMomOrganPrice,
		ShareMomOrganRate:   ShareMomOrganRate,
		ShareMomMemberPrice: ShareMomMemberPrice,
		ShareMomMemberRate:  ShareMomMemberRate,
		ShareOrganPrice:     ShareOrganPrice,
		ShareOrganRate:      ShareOrganRate,
		ShareMomLevel:       momLevel,
	}
	// 机构
	oss, err := oragnShare.Create()
	if err != nil {
		msg = "机构佣金插入异常"
		lognew.Error(context.TODO(), "OrderShareHandle5", lognew.Fields{"oid": oid, "msg": "机构佣金插入异常"})
		return false, msg
	}

	// 机构佣金 是否 大于30
	if organRate > 30 {
		organNowRate2 := (organRate - 30) / 100.0
		organNowPrice2 := organNowRate2 * orderInfo.OrderPrice
		// 记录佣金待退回
		os2 := models.OrderShare{
			OrderId:             orderInfo.OrderId,
			ShareName:           "机构",
			ShareStatus:         "10",
			ShareDesc:           "机构课程费用佣金/超出30%部分费用待退回",
			ShareInfo:           "",
			SharePrice:          organNowPrice2,
			ShareRate:           organNowRate2,
			ShareType:           "1",
			ShareUserId:         0,
			ShareTo:             1,
			ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
			ShareMomOrganPrice:  ShareMomOrganPrice,
			ShareMomOrganRate:   ShareMomOrganRate,
			ShareMomMemberPrice: ShareMomMemberPrice,
			ShareMomMemberRate:  ShareMomMemberRate,
			ShareOrganPrice:     ShareOrganPrice,
			ShareOrganRate:      ShareOrganRate,
			ShareMomLevel:       momLevel,
		}
		_, _ = os2.Create()
	}

	//拓展机构社区达人佣金分成
	if ShareMomOrganPrice > 0 && organMomId > 0 {
		// 获取 organMomId realName
		var meme models.Member
		mem, _ := meme.GetByID(organMomId)
		if mem.RealName == "" {
			mem.RealName = mem.NickName
		}
		// 记录佣金待退回
		os2 := models.OrderShare{
			OrderId:             orderInfo.OrderId,
			ShareName:           mem.RealName,
			ShareStatus:         "1",
			ShareDesc:           "拓展机构社区达人佣金分成",
			ShareInfo:           "",
			SharePrice:          ShareMomOrganPrice,
			ShareRate:           ShareMomOrganRate,
			ShareType:           "2",
			ShareUserId:         organMomId,
			ShareTo:             0,
			ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
			ShareMomOrganPrice:  ShareMomOrganPrice,
			ShareMomOrganRate:   ShareMomOrganRate,
			ShareMomMemberPrice: ShareMomMemberPrice,
			ShareMomMemberRate:  ShareMomMemberRate,
			ShareOrganPrice:     ShareOrganPrice,
			ShareOrganRate:      ShareOrganRate,
			ShareMomLevel:       momLevel,
		}
		_, _ = os2.Create()
	}

	//拓展用户 社区达人佣金分成
	if ShareMomMemberPrice > 0 && memberMomId > 0 {

		//配置佣金 获取当前比例
		shareRate := organRate * cfg.MomRate / 10000.0
		sharePrice := shareRate * orderInfo.OrderPrice
		if momRealName != "" {
			momRealName = "用户达人"
		}
		// 记录佣金待退回
		os2 := models.OrderShare{
			OrderId:             orderInfo.OrderId,
			ShareName:           momRealName,
			ShareStatus:         "1",
			ShareDesc:           "拓展用户社区达人佣金分成",
			ShareInfo:           "",
			SharePrice:          sharePrice,
			ShareRate:           shareRate,
			ShareType:           "3",
			ShareUserId:         memberMomId,
			ShareTo:             0,
			ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
			ShareMomOrganPrice:  ShareMomOrganPrice,
			ShareMomOrganRate:   ShareMomOrganRate,
			ShareMomMemberPrice: ShareMomMemberPrice,
			ShareMomMemberRate:  ShareMomMemberRate,
			ShareOrganPrice:     ShareOrganPrice,
			ShareOrganRate:      ShareOrganRate,
			ShareMomLevel:       momLevel,
		}
		_, _ = os2.Create()

		level, _ := tools.StringToInt(momLevel)
		// 用户等级
		if level > 0 {
			rate := 0.0
			for i := 1; i <= level; i++ {
				rate += cfg.MomExtraRate
			}
			if rate > cfg.MomExtraMax {
				rate = cfg.MomExtraMax
			}

			// 计算金额
			//配置佣金 获取当前比例
			shareRate := organRate * rate / 10000.0
			sharePrice := shareRate * orderInfo.OrderPrice

			if sharePrice > 0 {

				// 社区达人 用户等级拥挤分成
				os2 := models.OrderShare{
					OrderId:             orderInfo.OrderId,
					ShareName:           momRealName,
					ShareStatus:         "1",
					ShareDesc:           "拓展用户社区达人/等级阶段佣金分成/当前" + momLevel + "级",
					ShareInfo:           "",
					SharePrice:          sharePrice,
					ShareRate:           shareRate,
					ShareType:           "3",
					ShareUserId:         orderInfo.MemberMomId,
					ShareTo:             0,
					ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
					ShareMomOrganPrice:  ShareMomOrganPrice,
					ShareMomOrganRate:   ShareMomOrganRate,
					ShareMomMemberPrice: ShareMomMemberPrice,
					ShareMomMemberRate:  ShareMomMemberRate,
					ShareOrganPrice:     ShareOrganPrice,
					ShareOrganRate:      ShareOrganRate,
					ShareMomLevel:       momLevel,
				}
				_, err = os2.Create()
				if err != nil {
					lognew.Error(context.TODO(), "OrderShareHandle9", lognew.Fields{"err": err.Error(), "msg": "机构佣金插入异常"})

				}
			}

		}
	}

	//lognew.Error(context.TODO(), "OrderShareHandle10", lognew.Fields{"organInfo": organInfo, "type": organInfo.OrganMoneyType, "msg": "收支两条线"})

	// 收支两条线
	if organInfo.OrganMoneyType != "1" {
		//机构调用佣金 分成
		var wg sync.WaitGroup //定义一个同步等待的组
		wg.Add(1)             //为同步等待组增加一个成员
		go func() {
			OrderOrganShare(oss, orderInfo)
			defer wg.Done()
		}()
		wg.Wait()
	} else {

		// 生产 机构与平台的 佣金结算记录
		// 记录佣金待退回
		os2 := models.OrderShare{
			OrderId:             orderInfo.OrderId,
			ShareName:           "机构",
			ShareStatus:         "10",
			ShareDesc:           "机构佣金待支付平台/收支两条线",
			ShareInfo:           "",
			SharePrice:          ShareMomMemberPrice + ShareOrganPrice,
			ShareRate:           ShareMomMemberRate + ShareOrganRate,
			ShareType:           "1",
			ShareUserId:         0,
			ShareTo:             1,
			ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
			ShareMomOrganPrice:  ShareMomOrganPrice,
			ShareMomOrganRate:   ShareMomOrganRate,
			ShareMomMemberPrice: ShareMomMemberPrice,
			ShareMomMemberRate:  ShareMomMemberRate,
			ShareOrganPrice:     ShareOrganPrice,
			ShareOrganRate:      ShareOrganRate,
			ShareMomLevel:       momLevel,
		}
		_, _ = os2.Create()

		var wg sync.WaitGroup //定义一个同步等待的组
		wg.Add(1)             //为同步等待组增加一个成员
		go func() {
			OrderOrganShareFinish(oss, orderInfo)
			defer wg.Done()
		}()
		wg.Wait()

	}

	return true, ""
}

func AddOrganShare(organInfo models.Organ) {

	// 机构 分账 账户配置
	organAtt := organInfo.OrganPayType
	organAcc := organInfo.OrganPayAccount
	if organAtt == "" || organAcc == "" {
		// 商户分账失败通知
		return
	}

	//进行订单分账  分账接口进行分账
	refundData := &common.OrderAddShare{}
	refundData.SubMchId = organAcc
	//分账
	name := wechat.Server.WechatPay().Config().SubMchName
	if name == "" {
		name = "我们智慧（北京）科技有限公司"
	}
	item := common.OrderAddShareItem{
		Type:         "MERCHANT_ID",
		Account:      wechat.Server.WechatPay().Config().SubMchId,
		Name:         name,
		RelationType: "SERVICE_PROVIDER",
	}
	s, _ := json.Marshal(item)
	refundData.Receivers = string(s)
	res, err := wechat.Server.WechatPay().AddShare(refundData)
	if err != nil {
		lognew.Info(context.TODO(), "ShareAccountError", lognew.Fields{"res": res, "err": err.Error(), "refundData": refundData})
		return
	}
	lognew.Info(context.TODO(), "ShareAccount", lognew.Fields{"res": res, "refundData": refundData})
}

// --- @TODO 分账 分账
// OrderOrganShareFinish
func OrderOrganShareFinish(osInfo models.OrderShare, orderInfo models.Order) {

	// 机构 分账 账户配置
	//organAtt := orderInfo.OrganPayType
	organAcc := orderInfo.OrganPayAccount
	if organAcc == "" {
		lognew.Info(context.TODO(), "OrderOrganShareFinish-error", lognew.Fields{"res": "商户支付商户号配置为空", "orderInfo": orderInfo})

		// 商户分账失败通知
		notice.MsgOrderShare7(orderInfo.OrderId, fmt.Sprintf("%.2f", osInfo.SharePrice), "商户支付商户号配置为空") // 用户 用户确认排课
		return
	}
	// 订单支付激

	//进行订单分账  分账接口进行分账
	refundData := &common.OrderShareFinish{}
	refundData.TransactionId = orderInfo.PayNo
	refundData.OutTradeNo = GetTradeNo(orderInfo.OrderId, "S") //商户分账单号
	refundData.SubMchId = organAcc
	refundData.Description = "不需要分账"
	res, err := wechat.Server.WechatPay().ShareFinish(refundData)
	if err != nil {
		lognew.Info(context.TODO(), "OrderOrganShareFinishError", lognew.Fields{"res": res, "err": err.Error(), "refundData": refundData})
		return
	}
	lognew.Info(context.TODO(), "OrderOrganShareFinish", lognew.Fields{"res": res, "refundData": refundData})

	// 更新订单状态
	var oo models.Order
	oo.IsShare = "0"                   // OrderOrganShareFinish
	oo.ShareNo = refundData.OutTradeNo // 完结分账
	oo.ShareAccount = ""
	oo.ShareAccountPrice = 0
	oo.ShareTime = time.Now().Format("2006-01-02 15:04:05")
	_, _ = oo.Update(orderInfo.OrderId)

}

// 进行订单 分账
// 机构调用佣金 分成
func OrderOrganShare(osInfo models.OrderShare, orderInfo models.Order) {

	// 机构 分账 账户配置
	//organAtt := orderInfo.OrganPayType
	organAcc := orderInfo.OrganPayAccount
	if organAcc == "" {
		lognew.Info(context.TODO(), "OrderOrganShare-error", lognew.Fields{"res": "商户支付商户号配置为空", "orderInfo": orderInfo})

		// 商户分账失败通知
		notice.MsgOrderShare7(orderInfo.OrderId, fmt.Sprintf("%.2f", osInfo.SharePrice), "商户支付商户号配置为空") // 用户 用户确认排课
		return
	}
	// 订单支付激

	//进行订单分账  分账接口进行分账
	refundData := &common.OrderShare{}
	refundData.TransactionId = orderInfo.PayNo
	refundData.OutTradeNo = GetTradeNo(orderInfo.OrderId, "S") //商户分账单号
	refundData.SubMchId = organAcc
	//分账
	price := orderInfo.OrderPrice - osInfo.SharePrice // 订单金额 减去 分账佣金金额
	item := common.OrderShareItem{
		Type:        "MERCHANT_ID",
		Account:     wechat.Server.WechatPay().Config().SubMchId,
		Amount:      int(price * 100),
		Description: "机构订单佣金分成",
	}
	reciter := []common.OrderShareItem{
		item,
	}
	s, _ := json.Marshal(reciter)
	refundData.Receivers = string(s)
	res, err := wechat.Server.WechatPay().Share(refundData)
	if err != nil {
		lognew.Info(context.TODO(), "ShareOrderError", lognew.Fields{"res": res, "err": err.Error(), "refundData": refundData})
		return
	}
	lognew.Info(context.TODO(), "ShareOrder", lognew.Fields{"res": res, "refundData": refundData})

	// 跟新分账状态记录
	var share models.OrderShare
	share.ShareStatus = "5"
	share.ShareTime = time.Now().Format("2006-01-02 15:04:05")
	jd, _ := json.Marshal(res)
	share.ShareInfo = string(jd)
	_, _ = share.Update(osInfo.OrderShareId)

	// 更新订单状态
	var oo models.Order
	oo.IsShare = "1"                   // OrderOrganShare
	oo.ShareNo = refundData.OutTradeNo // 请求 分账服务
	oo.ShareAccount = item.Account
	oo.ShareAccountPrice = price
	oo.ShareOrganPrice = osInfo.SharePrice
	oo.ShareTime = time.Now().Format("2006-01-02 15:04:05")
	_, _ = oo.Update(orderInfo.OrderId)

	lognew.Info(context.TODO(), "OrderOrganShare-end", lognew.Fields{"osInfo": osInfo, "orderInfo": orderInfo})

}

// 用户等级变动 触发订单更新
func OrderShareMomHandle(momId int, momName string, noeLevel int) {
	var pageSize = 100
	var pageIndex = 1
	// 查询 社区达人的订单
	var odr models.Order
	orderList, count, err := odr.GetMomList(pageSize, pageIndex, momId)
	if err != nil {
		return
	}
	if len(orderList) <= 0 {
		return
	}
	page := (count / pageSize) + 1

	for _, v := range orderList {
		doOneOrderLevel(v, momId, momName, noeLevel)
	}

	if page > 1 {
		for i := 2; i <= page; i++ {
			orderList, _, _ := odr.GetMomList(pageSize, pageIndex, momId)
			if len(orderList) <= 0 {
				break
			}
			for _, v := range orderList {
				doOneOrderLevel(v, momId, momName, noeLevel)
			}
		}
	}
}

func doOneOrderLevel(orderInfo models.Order, momId int, momName string, noeLevel int) {
	//订单待分账 下单时 后台配置分账比例
	llevel := tools.IntToString(noeLevel)
	var orderS models.OrderShare
	orderS.OrderId = orderInfo.OrderId
	firstInfo, err := orderS.Get()
	if err != nil {
		return
	}

	var cfg models.CommonCfgData
	_ = json.Unmarshal([]byte(orderInfo.ShareCfg), &cfg)
	//计算单词level 钱
	if cfg.MomExtraRate == "" {
		return
	}
	rate := tools.StringToFloat64(err, cfg.MomExtraRate)
	//插入流水表
	// 计算金额
	//配置佣金 获取当前比例
	shareRate := (100 - firstInfo.ShareOrganRate) * rate / 100.0
	sharePrice := shareRate * orderInfo.OrderPrice

	if sharePrice <= 0 {
		return
	}
	// 社区达人 用户等级拥挤分成
	os2 := models.OrderShare{
		OrderId:             orderInfo.OrderId,
		ShareName:           momName,
		ShareStatus:         "1",
		ShareDesc:           "拓展用户社区达人/等级阶段佣金分成/当前" + llevel + "级/",
		ShareInfo:           "",
		SharePrice:          sharePrice,
		ShareRate:           shareRate,
		ShareType:           "3",
		ShareUserId:         orderInfo.MemberMomId,
		ShareTo:             0,
		ShareTime:           time.Now().Format("2006-01-02 15:04:05"),
		ShareMomOrganPrice:  firstInfo.ShareMomOrganPrice,
		ShareMomOrganRate:   firstInfo.ShareMomOrganRate,
		ShareMomMemberPrice: firstInfo.ShareMomMemberPrice,
		ShareMomMemberRate:  firstInfo.ShareMomMemberRate,
		ShareOrganPrice:     firstInfo.ShareOrganPrice,
		ShareOrganRate:      firstInfo.ShareOrganRate,
		ShareMomLevel:       llevel,
	}
	_, _ = os2.Create()
}
